#include "C06.h"
#include <assert.h>
#include <stdio.h>
#include <string.h>

void reverse(int *arX, int count)
{
    for(int i=0; i < count/2; i++)
    {
        int tmp = arX[i];
        arX[i] = arX[count-i-1];
        arX[count-i-1] = tmp;
    }
}

void sort_ascent(int *arX, int count)
{
    for(int i=0;i<count;i++){
        for(int j=i+1;j<count;j++){
            if(arX[i] > arX[j]){
                int tmp = arX[i];
                arX[i] = arX[j];
                arX[j] = tmp;
            }
        }
    }
}

void delete_elements_at_begin(short *arSrc, int countSrc, short *arResult, int countResult)
{
    // make sure countResult is not greater than countSrc
    assert(countResult <= countSrc);

    int offset = countSrc - countResult;
    for(int i=0;i<countResult;i++){
        arResult[i] = arSrc[i+offset];
    }
}

void delete_elements_at_pos(short *arSrc, int countSrc, short *arResult, int countResult, int pos)
{
    assert(pos < countSrc);
    assert(countSrc-countResult <= countSrc-pos);

    int posA = pos;
    int posB = pos + (countSrc - countResult) - 1;
    int i=0, j=0;
    while(i < countSrc && j < countResult){
        if(i >= posA && i <= posB){
            i++;
            continue;
        }

        arResult[j] = arSrc[i];
        i++, j++; 
    }
}

void combine_strings(char *szLeft, char *szRight, char *arResult)
{
    sprintf(arResult, "%s%s", szLeft, szRight);
}

int find_pos(char *szSrc, char x)
{
    char *p = szSrc;
    while(*p != 0){
        if(*p == x) return p-szSrc;
        p++;
    }

    return -1;
}

void insert(char *szResult, int countResult, char *szSrc, int pos, char *szIns)
{
    int i=0, j=0;
    while(i < countResult-1){
        if(i < pos){
            szResult[i] = szSrc[j];
            i++, j++;
        }
        else if(i < pos + strlen(szIns)){
            szResult[i] = szIns[i-pos];
            i++;
        }
        else{
            szResult[i] = szSrc[j];
            i++, j++;
        }
    }

    // for safe
    szResult[countResult - 1] = 0;
}